# routers/hot_index_history.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from db import HotIndexHistory
from pydantic import BaseModel

router = APIRouter(prefix="/hot-index-history", tags=["hot_index_history"])

# Pydantic 模型定义
class HotIndexHistoryCreate(BaseModel):
    product_id: int
    period: str
    index_value: int

class HotIndexHistoryResponse(HotIndexHistoryCreate):
    id: int
    
    class Config:
        orm_mode = True

# 依赖项
def get_db():
    from db import SessionLocal
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# HotIndexHistory 相关 API
@router.post("/", response_model=HotIndexHistoryResponse)
def create_hot_index_history(history: HotIndexHistoryCreate, db: Session = Depends(get_db)):
    db_history = HotIndexHistory(**history.dict())
    db.add(db_history)
    db.commit()
    db.refresh(db_history)
    return db_history

@router.get("/", response_model=List[HotIndexHistoryResponse])
def read_hot_index_histories(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    histories = db.query(HotIndexHistory).offset(skip).limit(limit).all()
    return histories

@router.get("/{history_id}", response_model=HotIndexHistoryResponse)
def read_hot_index_history(history_id: int, db: Session = Depends(get_db)):
    db_history = db.query(HotIndexHistory).filter(HotIndexHistory.id == history_id).first()
    if db_history is None:
        raise HTTPException(status_code=404, detail="Hot index history not found")
    return db_history

@router.put("/{history_id}", response_model=HotIndexHistoryResponse)
def update_hot_index_history(history_id: int, history: HotIndexHistoryCreate, db: Session = Depends(get_db)):
    db_history = db.query(HotIndexHistory).filter(HotIndexHistory.id == history_id).first()
    if db_history is None:
        raise HTTPException(status_code=404, detail="Hot index history not found")
    
    for key, value in history.dict().items():
        setattr(db_history, key, value)
        
    db.commit()
    db.refresh(db_history)
    return db_history

@router.delete("/{history_id}", response_model=HotIndexHistoryResponse)
def delete_hot_index_history(history_id: int, db: Session = Depends(get_db)):
    db_history = db.query(HotIndexHistory).filter(HotIndexHistory.id == history_id).first()
    if db_history is None:
        raise HTTPException(status_code=404, detail="Hot index history not found")
    
    db.delete(db_history)
    db.commit()
    return db_history